import { defineService } from '../../../../src/index'
import jwt from '../../../../src/middleware'

export default defineService({
  schema: {
    query: {
      code: {
        type: 'string',
        desc: '微信客户端获取的code',
      },
    },
  },
  async handler(ctx) {
    const appid = 'wx111111111111111'
    const secret = 'sgh415hsfgh4s5dj1dt5ygj4jmdgh4sg'
    const { code } = ctx.query

    const api = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`
    // 通过 wx.login 接口获得临时登录凭证 code 后
    const { session_key, openid } = await fetch(api).then(res => res.json())

    // 连接数据库查询用户信息
    const user = await findUserInfo(openid)
    if (!user) {
      ctx.json({
        code: '003',
        msg: '用户不存在',
      })
      return
    }
    return ctx.json({
      code: '001',
      msg: '登录成功',
      data: {
        ...user,
        token: jwt.sign({ user }, 'secret', { expiresIn: 60 * 60 }),
        session_key,
      },
    })
  },
})

function findUserInfo(openid) {
  return { openid, id: 1, name: '张三' }
}
